package com.situ.skymallcartapi.service.impl;

import com.situ.model.Cart;
import com.situ.model.Product;
import com.situ.service.CartService;
import com.situ.skymallcartapi.dao.CartMapper;
import com.situ.skymallcartapi.service.ProductFeignService;
import com.situ.utils.JsonResult;
import com.situ.utils.XinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CartServiceImpl  implements CartService {
  private CartMapper cartMapper;
  private ProductFeignService productFeignService;

    @Autowired
    public void setCartMapper(CartMapper cartMapper) {
        this.cartMapper = cartMapper;
    }

    @Autowired
    public void setProductFeignService(ProductFeignService productFeignService) {
        this.productFeignService = productFeignService;
    }

    @Override
    public List<Cart> findByUserId(Integer userId) {
       Cart cart = new Cart();
       cart.setUserId(userId);

       List<Cart> carts=cartMapper.findBy(cart);
       carts.forEach(this::findProduct);
        return carts;
    }

    @Override
    public Cart findById(Integer id) {
        Cart cart= cartMapper.selectById(id);
        findProduct(cart);
        return cart;
    }

    private void findProduct(Cart cart){
        ResponseEntity<JsonResult<Product>> resp=productFeignService.findById(cart.getProductId());
        JsonResult<?> jr=resp.getBody();
        if(jr!=null&&jr.isSuccess()){
            cart.setProduct((Product) jr.getData());
        }
    }


    @Override
    public boolean save(Cart cart) {
       List<Cart> items=cartMapper.findBy(cart);
       if(XinUtils.isNotEmpty(items)){
           Cart carts=items.getFirst();
           carts.setQuantity(carts.getQuantity()+cart.getQuantity())
           return cartMapper.updateById(carts)>0;
       }else {
           return cartMapper.insert(cart) > 0;
       }
    }

    @Override
    public boolean update(Cart cart) {
        return cartMapper.updateById(cart) > 0;
    }

    @Transactional(rollbackFor = Exception.class,
           isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRES_NEW)
    @Override
    public int deleteByIds(List<Integer> ids) {
        int count=0;
        for(Integer id:ids){
            count+=cartMapper.deleteById(id);
        }
        return count;
    }
}
